package com.liuzy.server;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 服务监听端口等待客户端连接
 * 
 * @author liuzy
 * @version 2015年5月1日
 */
public class Server {

	private static final String LOG_FILE = "D:/liuzy.log";
	
	private static ServerSocket server = null;
	
	private static PrintWriter log = null;

	private static int port = 8189;

	private static boolean isRun = true;

	private static Map<String, Task> taskMap = new HashMap<>();

	private static int id = 0;

	private Server() {

	}
	
	public static void startup() {
		startup(port);
	}

	public static void startup(int port) {
		Server.port = port;
		try {
			server = new ServerSocket(port);
			log("监听已启动,端口" + port + "!");
			Socket socket = null;
			Task task = null;
			while (isRun) {
				socket = server.accept();
				++id;
				task = new Task(socket, id);
				taskMap.put("task" + id, task);
				task.start();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void shutdown() {
		isRun = false;
		for (String key : taskMap.keySet()) {
			Task task = taskMap.get(key);
			task.stopTask();
		}
		try {
			// 用此办法让Server停止等待accept
			new Socket("localhost", port).shutdownOutput();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void stopTask(int id) {
		Task task = taskMap.get("task" + id);
		task.stopTask();
		removeTask(id);
	}

	public static void removeTask(int id) {
		taskMap.remove("task" + id);
	}

	public static String getStatus() {
		StringBuffer sb = new StringBuffer();
		sb.append("**************\r\n已连接客户端数量 ").append(taskMap.size()).append("\r\n").append(taskMap.toString()).append("\r\n**************\r\n");
		return sb.toString();
	}

	public static void log(String info) {
		System.out.println(info);
		File file = new File(LOG_FILE);
		try {
			if (!file.exists()) {
				file.createNewFile();
			}
			log = new PrintWriter(new FileOutputStream(file, true));
		} catch (Exception e) {
			e.printStackTrace();
		}
		log.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ").format(new Date()) + info);
		log.flush();
		log.close();
	}
}
